package tools

import (
	"crypto/md5"
	"crypto/rand"
	"crypto/sha1"
	"encoding/base64"
	"fmt"
	"io"
	"sync"
	"time"

	"github.com/go-redis/redis"
)

const SessionPrefix = "lt_sess_"

var RedisClientMap = map[string]*redis.Client{}
var syncLock sync.Mutex

func CreateSessionId(sessionId string) string {
	return SessionPrefix + sessionId
}

func GetSessionIdByUserId(userId int) string {
	return fmt.Sprintf(SessionPrefix+"map_%d", userId)
}

func GetSessionName(sessionId string) string {
	return SessionPrefix + sessionId
}

func Sha1(s string) string {
	h := sha1.New()
	h.Write([]byte(s))
	bs := h.Sum(nil)
	return fmt.Sprintf("%x", bs)
}

func Md5(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	bs := h.Sum(nil)
	return fmt.Sprintf("%x", bs)
}

func GetNowDateTime() string {
	return time.Unix(time.Now().Unix(), 0).Format("2006-01-02 15:04:05")
}

func GetRandomToken(length int) string {
	r := make([]byte, length)
	io.ReadFull(rand.Reader, r)
	return base64.URLEncoding.EncodeToString(r)
}

type R map[string]interface{}

type RedisOption struct {
	Address  string
	Password string
	Db       int
}

func GetRedisInstance(opt RedisOption) *redis.Client {
	syncLock.Lock()
	if redisCli, ok := RedisClientMap[opt.Address]; ok {
		syncLock.Unlock()
		return redisCli
	}
	client := redis.NewClient(&redis.Options{
		Addr:       opt.Address,
		Password:   opt.Password,
		DB:         opt.Db,
		MaxConnAge: 20 * time.Second,
	})
	RedisClientMap[opt.Address] = client
	syncLock.Unlock()
	return client
}
